from rest_framework import serializers
from user.models import User
from django_redis import get_redis_connection
from rest_framework_jwt.settings import api_settings
import re
from question.models import Label
from article.serializers import ArticleSerializerForList
from question.serializers import LabelSerializerSimple, QuestionSerializerForList, ReplySerializerForList
from recruit.serializer import EnterpriseSerializerSimple
import requests
from lxml import etree
# 设置请求的url
url = 'http://127.0.0.1:8080/index.html'
# 获取页面源码
ret = requests.get(url=url).text
# 解析数据
tree = etree.HTML(ret)
a = tree.xpath('//*[@id="myCarousel"]/div/div[1]/a/img/@src')[0]
# 拼接图片url
img_url = 'http://127.0.0.1:8080' + a[(a.find('.')+1):]



#创建用户的序列化器
class CreateUserSerializer(serializers.ModelSerializer):
    sms_code = serializers.CharField(label='短信验证码', write_only=True)
    token = serializers.CharField(label='JWT token', read_only=True)

    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'sms_code', 'mobile', 'token', 'avatar')
        extra_kwargs = {
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }
    #验证手机号
    def validate_mobile(self, value):
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')
        return value


    #判断短信验证码
    def validate(self, data):
        # 与数据库进行连接，判断是否有验证码
        redis_conn = get_redis_connection('verify_codes')
        #取出mobile
        mobile = data['mobile']
        #取出验证码
        real_sms_code = redis_conn.get('sms_%s' % mobile)
        #判断
        if real_sms_code is None:
            raise serializers.ValidationError('无效的短信验证码')
        if data['sms_code'] != real_sms_code.decode():
            raise serializers.ValidationError('短信验证码错误')

        return data
    #
    #
    #重写保存方法，增加密码加密
    def create(self, validated_data):

        # 移除数据库模型类中不存在的属性
        del validated_data['sms_code']
        # 我们默认不传avatar，前端默认返回固定的图片
        # 现在我们在新建用户时，传入avatar字段，作为默认的头像
        validated_data['avatar'] = img_url
        user = super().create(validated_data)
        user.set_password(validated_data['password'])
        user.save()

        # 组织payload数据的方法
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        # 生成jwt token数据的方法
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        # 组织payload数据
        payload = jwt_payload_handler(user)
        # 生成jwt token
        token = jwt_encode_handler(payload)
        # 给user对象增加属性，保存jwt token的数据
        user.token = token

        return user




#用户修改擅长技术的序列化器
class UserLabelSerializer(serializers.ModelSerializer):
    labels = serializers.PrimaryKeyRelatedField(
        required=True, many=True, queryset=Label.objects.all()
    )

    class Meta:
        model = User
        fields = ('id', 'labels')



#用户详细信息序列化器
class UserDetailSerializer(serializers.ModelSerializer):

    labels = LabelSerializerSimple(required=False, many=True)
    username = serializers.CharField(read_only=True)
    questions = QuestionSerializerForList(read_only=True, many=True)
    answer_question = ReplySerializerForList(read_only=True, many=True)
    collected_articles = ArticleSerializerForList(read_only=True, many=True)
    enterpises = EnterpriseSerializerSimple(read_only=True, many=True)

    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'realname',
        'birthday', 'sex', 'avatar', 'website',
        'email', 'city', 'address', 'labels', 'questions',
        'answer_question', 'collected_articles', 'enterpises')

    # def Update(self):




#用户修改密码序列化器
class UserPwdSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['password']
        extra_kwargs = {
            'password': {'write_only': True}
        }
    def update(self, instance, validated_data):
        user = super().update(instance, validated_data)
        user.set_password(validated_data['password'])
        user.save()
        return user


